package tcln.gxtx.client.widget.toolbar;

import tcln.gxtx.client.utils.async.DeferredCommandScheduler;

import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.RequiresResize;

/**
 * An extended version of GXT {@link ToolBar} which allows itself to fit in its parent element using GWT
 * {@link RequiresResize} mechanism.
 * 
 * @author Truong Chau Lien Ngoc (lienngoc@gmail.com)
 */
public class ResizableToolBar extends ToolBar implements RequiresResize {
    private boolean resizeEnabled = true;

    /**
     * @param resizeEnabled
     */
    public ResizableToolBar(boolean resizeEnabled) {
        this.resizeEnabled = resizeEnabled;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public final void onResize() {
        if (resizeEnabled) {
            DeferredCommandScheduler.scheduleOnce(new Command() {
                @Override
                public void execute() {
                    deferredResize();
                }
            });
        }
    }

    private void deferredResize() {
        int h = DOM.getElementPropertyInt(getParent().getElement(), "clientHeight");
        int w = DOM.getElementPropertyInt(getParent().getElement(), "clientWidth");
        if (h > 0) {
            setSize(w, h);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void afterRender() {
        super.afterRender();
        onResize();
    }
}
